#!/bin/bash
#
# build-appliance - build or update a test appliance
#
# For details, see usage() and Documentation/building-rootfs.md

set -e -u

gen_image_args=
OUT_TAR=
DATECODE=
BUILD_ENV=
SUDO_ENV=sudo
DO_GCE=

if test -f config.custom ; then
    . config.custom
else
    . config
fi

. run-fstests/util/arch-funcs

set_default_arch

usage()
{
    cat <<EOF
Usage: build-appliance [OPTION]...
Build or update a test appliance.

Options:
    --chroot=CHROOT Use the specified build chroot, where CHROOT is the chroot
                    name in /etc/schroot/schroot.conf, e.g. "stretch-amd64".
    --gce           Build a GCE test appliance as well as a kvm/android
                    test appliance
    --out-tar       Build a root_fs.tar.gz, not a root_fs.img
    --no-out-tar    Build/update a root_fs.img, not a root_fs.tar.gz
    --update        Update only; don't do a clean build.  (Only supported with
                    .img output currently.)
EOF
}

UPDATE=false

longopts="help"
longopts+=",chroot:"
longopts+=",out-tar"
longopts+=",no-out-tar"
longopts+=",update"
longopts+=",gce"
longopts+=",datecode:"

if ! options=$(getopt -o "" -l "$longopts" -- "$@"); then
    usage 1>&2
    exit 2
fi

eval set -- "$options"
while (( $# >= 0 )); do
    case "$1" in
    --help)
	usage
	exit 0
	;;
    --chroot)
	BUILD_ENV="schroot -c $2 --"
	SUDO_ENV="schroot -c $2 -u root --"
	MY_ARCH=$(schroot -c $2 -- dpkg --print-architecture)
	shift
	;;
    --out-tar)
	OUT_TAR=yes
	;;
    --no-out-tar)
	OUT_TAR=
	;;
    --update)
	UPDATE=true
	;;
    --gce)
	DO_GCE=yes
	;;
    --datecode) shift
	DATECODE="$1"
	;;
    --)
	shift
	break
	;;
    *)
	echo 1>&2 "Invalid option: \"$1\""
	usage 1>&2
	exit 2
	;;
    esac
    shift
done

if $UPDATE && [ "$OUT_TAR" = "yes" ]; then
    echo 1>&2 "--update is only supported with .img output currently!"
    exit 1
fi

set_my_arch
set_canonicalized_arch "$MY_ARCH"

cd fstests-bld

if $UPDATE; then
    $BUILD_ENV ./update-all
    gen_image_args+=" --update"
else
    $BUILD_ENV make all-clean-first
fi
$BUILD_ENV ./gen-tarball

case "$OUT_TAR" in
    both) gen_image_args+=" --both" ;;
    yes)  gen_image_args+=" --out-tar" ;;
esac

cd ../run-fstests
if test -n "$DO_GCE"; then
    d=
    if test -n "$DATECODE" ; then
	d="--datecode $DATECODE"
    fi
    ./gce-xfstests create-image --arch=$ARCH $d \
		   >& /tmp/gce-xfstests-create.$$ &
fi

cd ../test-appliance
$SUDO_ENV ./gen-image $gen_image_args

if test -n "$DO_GCE"; then
    tail -n +1 -f /tmp/gce-xfstests-create.$$ &
    wait %./gce-xfstests
    kill %tail
    rm -f /tmp/gce-xfstests-create.$$
fi
